from collections import defaultdict
#简单无向无权图的定义：用连接表，不能有自环边(自己套自己)和平行边(两个顶点相互套)。

class graph:
    def __init__(self,file=None,v=None,e=None):
        self.fileName = file
        self.__GMatrix = None
        self.__V = v
        self.__E = e
    #下面是查看实列私有的属性，但是不能修改
    @property
    def getV(self):
        return self.__V
    @property
    def getE(self):
        return self.__E

    def __valid(self,v):
        '''
        :param v: int
        :return: 判断文件中顶点有效性
        '''
        if v<0 or v>self.__V:
            raise "顶点不存在"
        return
    def readGraph(self):
        '''
        :return: 读取文件中的关于图的信息，创建矩阵
        '''
        try:
            with open(self.fileName,"r") as f:
                s = f.readlines()#读取所有的行
                # 将一行中的换行符及空格去掉，方便我们取值
                genRa = ( i.strip("\n").strip().replace(" ","",i.count(" ")) for i in s)
                V_E = next(genRa)
                self.__V = int(V_E[0])
                self.__E = int(V_E[1])
                #这里的list是否可以优化
                self.__GMatrix = defaultdict(list)
                for i in genRa:
                    a = int(i[0])
                    b = int(i[1])
                    self.__valid(a)
                    self.__valid(b)
                    if a == b:
                        raise "不能有自环"
                    if b in self.__GMatrix[a]:
                        raise "不能平行"
                    self.__GMatrix[a].append(b)
                    self.__GMatrix[b].append(a)
            return self.__GMatrix
        except BaseException as e:
            print(e.__repr__())
    def hasEdge(self,a,b):
        if isinstance(a,int) and isinstance(b,int):
            self.__valid(a)
            self.__valid(b)
            return b in self.__GMatrix[a]
        else:
            raise "顶点不合法"
    def adjacentVertices(self,v):
       if isinstance(v,int):
           self.__valid(v)
           return self.__GMatrix[v]
       else:
           raise "顶点不合法"
    def degree_of_vertic(self,v):
        return len(self.adjacentVertices(v))
if __name__ == '__main__':
    g = graph(r"D:\tensorflow2_pytorch\python算法\Graph\LJT.txt")
    print(g.readGraph())
    print(g._graph__E)
    print(g._graph__V)
    print(g.hasEdge(1, 6))
    print(g.adjacentVertices(1))
    print(g.degree_of_vertic(1))
